<template>
  <div class="logs-page">
    <div class="page-container">
      <div class="page-header">
        <h2 class="page-title">日志管理</h2>
        <div class="header-actions">
          <el-button @click="showExportDialog = true">
            <el-icon><Download /></el-icon>
            导出日志
          </el-button>
          <el-button @click="fetchLogs">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>

      <!-- 过滤条件 -->
      <div class="filter-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="filters.search"
              placeholder="搜索日志内容"
              @input="handleSearch"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select v-model="filters.level" placeholder="日志级别" @change="fetchLogs" clearable>
              <el-option label="全部" value="" />
              <el-option label="info" value="info" />
              <el-option label="warning" value="warning" />
              <el-option label="error" value="error" />
              <el-option label="debug" value="debug" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-select v-model="filters.step" placeholder="执行步骤" @change="fetchLogs" clearable>
              <el-option label="全部" value="" />
              <el-option label="clone" value="clone" />
              <el-option label="sync" value="sync" />
              <el-option label="verify" value="verify" />
              <el-option label="rollback" value="rollback" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DDTHH:mm:ss"
              @change="handleDateChange"
            />
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="fetchLogs">搜索</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 日志列表 -->
      <el-table
        :data="logs"
        v-loading="loading"
        element-loading-text="加载中..."
        empty-text="暂无日志"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="execution_id" label="执行ID" width="100" />
        <el-table-column prop="level" label="级别" width="80">
          <template #default="scope">
            <el-tag :type="getLogLevelType(scope.row.level)">
              {{ scope.row.level.toUpperCase() }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="step" label="步骤" width="100">
          <template #default="scope">
            <el-tag>{{ scope.row.step }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="message" label="消息" show-overflow-tooltip />
        <el-table-column prop="created_at" label="时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button size="small" @click="viewLogDetail(scope.row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[20, 50, 100, 200]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 导出对话框 -->
    <el-dialog v-model="showExportDialog" title="导出日志" width="500px">
      <el-form :model="exportForm" label-width="100px">
        <el-form-item label="导出格式">
          <el-radio-group v-model="exportForm.format">
            <el-radio label="json">JSON</el-radio>
            <el-radio label="csv">CSV</el-radio>
            <el-radio label="txt">TXT</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="包含当前过滤条件">
          <el-switch v-model="exportForm.useFilters" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showExportDialog = false">取消</el-button>
        <el-button type="primary" @click="exportLogs" :loading="exportLoading">
          导出
        </el-button>
      </template>
    </el-dialog>

    <!-- 日志详情对话框 -->
    <el-dialog v-model="showDetailDialog" title="日志详情" width="800px">
      <div v-if="selectedLog">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="ID">{{ selectedLog.id }}</el-descriptions-item>
          <el-descriptions-item label="执行ID">{{ selectedLog.execution_id }}</el-descriptions-item>
          <el-descriptions-item label="级别">
            <el-tag :type="getLogLevelType(selectedLog.level)">
              {{ selectedLog.level.toUpperCase() }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="步骤">
            <el-tag>{{ selectedLog.step }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="仓库ID">{{ selectedLog.repo_id || '-' }}</el-descriptions-item>
          <el-descriptions-item label="时间">{{ formatDateTime(selectedLog.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="消息" :span="2">
            {{ selectedLog.message }}
          </el-descriptions-item>
          <el-descriptions-item label="详细信息" :span="2" v-if="selectedLog.details">
            <pre>{{ JSON.stringify(selectedLog.details, null, 2) }}</pre>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { logApi } from '../api'

const logs = ref([])
const loading = ref(false)
const showExportDialog = ref(false)
const showDetailDialog = ref(false)
const selectedLog = ref(null)
const exportLoading = ref(false)
const dateRange = ref([])

const filters = reactive({
  search: '',
  level: '',
  step: '',
  start_time: '',
  end_time: ''
})

const pagination = reactive({
  page: 1,
  size: 50,
  total: 0
})

const exportForm = reactive({
  format: 'json',
  useFilters: true
})

const fetchLogs = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...filters
    }

    const response = await logApi.getLogs(params)
    logs.value = response.data?.items || []
    pagination.total = response.data?.total || 0
  } catch (error) {
    console.error('获取日志列表失败:', error)
    ElMessage.error('获取日志列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  fetchLogs()
}

const handleDateChange = (dates) => {
  if (dates && dates.length === 2) {
    filters.start_time = dates[0]
    filters.end_time = dates[1]
  } else {
    filters.start_time = ''
    filters.end_time = ''
  }
  fetchLogs()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  fetchLogs()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  fetchLogs()
}

const getLogLevelType = (level) => {
  const typeMap = {
    info: 'info',
    warning: 'warning',
    error: 'danger',
    debug: 'success'
  }
  return typeMap[level] || 'info'
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

const viewLogDetail = (log) => {
  selectedLog.value = log
  showDetailDialog.value = true
}

const exportLogs = async () => {
  exportLoading.value = true
  try {
    const params = {
      format: exportForm.format
    }

    if (exportForm.useFilters) {
      Object.assign(params, filters)
    }

    const response = await logApi.downloadLogs(params)

    // 创建下载链接
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `logs_${new Date().toISOString().split('T')[0]}.${exportForm.format}`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)

    ElMessage.success('日志导出成功')
    showExportDialog.value = false
  } catch (error) {
    console.error('导出日志失败:', error)
    ElMessage.error('导出日志失败')
  } finally {
    exportLoading.value = false
  }
}

onMounted(() => {
  fetchLogs()
})
</script>

<style scoped>
.header-actions {
  display: flex;
  gap: 12px;
}

.filter-section {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

pre {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
  max-height: 300px;
}
</style>